"use server"
import { redirect } from "next/navigation"
import { addProduct, deleteProduct, updateProduct } from "@/prisma-db"
import { revalidatePath } from "next/cache"

export type Errors = {
    title?: string,
    price?: string,
    description?: string
}

export type FormState = {
    errors: Errors
}

// useActionState 传递给服务端 Action 的第一个参数是上一次的状态，第二个参数是当前的 FormData。
export async function createProduct(prevState: FormState, formdata: FormData) {
    const title = formdata.get("title") as string;
    const price = formdata.get("price") as string;
    const description = formdata.get("description") as string;

    const errors: Errors = {};
    if (!title) {
        errors.title = "Title is required";
    }
    if (!price) {
        errors.price = "Price is required";
    }
    if (!description) {
        errors.description = "Description is required";
    }
    if (Object.keys(errors).length > 0) {
        return { errors };
    }

    await addProduct(title, parseInt(price), description);
    redirect("/products-db");
};

export async function editProduct(
    id: number,
    prevState: FormState,
    formdata: FormData
) {
    const title = formdata.get("title") as string;
    const price = formdata.get("price") as string;
    const description = formdata.get("description") as string;
    const errors: Errors = {};
    if (!title) {
        errors.title = "Title is required";
    }
    if (!price) {
        errors.price = "Price is required";
    }
    if (!description) {
        errors.description = "Description is required";
    }
    if (Object.keys(errors).length > 0) {
        return { errors };
    }
    await updateProduct(id, title, parseInt(price), description);
    redirect("/products-db");
};

export async function removeProduct(id: number) {
    await deleteProduct(id);
    revalidatePath("/products-db");
};